// 云函数入口文件
const cloud = require('wx-server-sdk')
const moment = require("moment")

cloud.init()
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let {
    OPENID
  } = wxContext
  let {
    id,
    status,
    extraPoint,
    comment
  } = event
  var success = false
  var message = "登录失败"

  console.log(event)

  const db = cloud.database()
  var cards = await db.collection('cards').where({
    _id: id
  }).get()
  if (cards.data.length != 0) {
    if (cards.data[0].status != 'unChecked') {
      return {
        success: false,
        message: '已有其他教练审核了哦'
      }
    }
    let card = cards.data[0];
    let exPoint = card.point


    if (extraPoint) {
      exPoint = parseInt(card.point) + parseInt(extraPoint)
    } else {
      extraPoint = 0
    }
    console.log("exPoint:" + exPoint)
    console.log("extraPoint:" + extraPoint)

    await db.collection('cards').where({
      _id: id
    }).update({
      data: {
        status: status,
        point: exPoint,
        comment: comment
      }
    }).then(res => {
      success = true
      message = "审核成功"
    }, error => {
      console.log(error)
      success = false
      message = "审核失败，请联系管理员"
    })


    var checkedStatus = status == 'checked' ? '审核通过' : '审核失败'
    var commentContent = comment.content ? comment.content : '你的打卡已经' + checkedStatus

    moment.locale('zh-cn');
    var dateStr = moment().add(8, 'hours').format('YYYY年MM月DD HH:mm')
    console.log('checkedStatus', checkedStatus)
    console.log('commentContent', commentContent)
    console.log('dateStr', dateStr)
    try {
      const result = await cloud.openapi.subscribeMessage.send({
        touser: card._openid, // 通过 getWXContext 获取 OPENID
        page: 'pages/card/mycard/myCard',
        data: {
          phrase1: {
            value: checkedStatus
          },
          thing2: {
            value: commentContent
          },
          time13: {
            value: dateStr
          }
        },
        templateId: 'zp2xRCcbAwjvgfz2ZBxpnd23F-6nN5fKPxrfzraTikc',
        formId: OPENID,
      })
    } catch (err) {
      console.log(err)
    }
  }

  if (success && status == 'checked') {
    let card = cards.data[0];
    let user = await db.collection('user').where({
      _openid: card._openid
    }).get()
    var rules = await db.collection('rules').where({
      team: user.data[0].team
    }).get()


    var addPoint = 0
    moment.locale('zh-cn');
    var m = moment().utcOffset(480)
    m.set({
      hour: 0,
      minute: 0,
      second: 0,
      millisecond: 0
    })
    const startWeekDate = m.week(moment().week()).startOf('week').valueOf();
    // //TODO addCard 函数系统时间多存了8小时 这个星期临时处理下
    // const startWeekDate = startWeek + 8 * 60 * 60 * 1000;
    const endWeekDate = m.week(moment().week()).endOf('week').valueOf();
    const _ = db.command
    console.log('card._id', card._id)
    let postCards = await db.collection('cards').where({
      _openid: card._openid,
      _id: _.neq(card._id),
      type: card.type,
      systemTime: _.lte(endWeekDate).and(_.gte(startWeekDate)),
    }).get()

    var totalTypePoint = 0
    for (var i = 0; i < postCards.data.length; i++) {
      let pCard = postCards.data[i]
      if (pCard.status == "checked") {
        totalTypePoint += pCard.point
      }
    }
    console.log('postCards', postCards)
    console.log('totalTypePoint', totalTypePoint)
    addPoint = calculatePoint(user.data[0], rules, card, totalTypePoint);

    let point = user.data[0].point + addPoint + parseInt(extraPoint);
    console.log('user.data[0].point', user.data[0].point)
    console.log('point', point)
    await db.collection('user').where({
      _openid: card._openid
    }).update({
      data: {
        point: point
      }
    }).then(res => {
      console.log('res', res)
      success = true
      message = "审核成功"
    }, error => {
      console.log('error', error)
      success = false
      message = "审核失败，请联系管理员"
    })

    var userData = await db.collection('userInfo').where({
      _openid: card._openid
    }).get()

    let userInfo = userData.data[0]
    var distance = card.distance;
    if (!distance) {
      distance = 0
    }
    var time = card.time;
    if (!time) {
      time = 0
    }
    var calorie = card.calorie;
    if (!calorie) {
      calorie = 0
    }
    if (userInfo) {
      distance = parseFloat(userInfo.distance) + parseFloat(distance)
      distance = distance.toFixed(2)
      time = parseInt(userInfo.time) + parseInt(time)
      calorie = parseInt(userInfo.calorie) + parseInt(calorie)
      infoPoint = userInfo.point + addPoint + parseInt(extraPoint)
      await db.collection('userInfo').where({
        _openid: card._openid
      }).update({
        data: {
          point: infoPoint,
          distance: distance,
          calorie: calorie,
          time: time
        },
      }).then(res => {
        console.log('res', res)
        success = true
        message = "审核成功"
      }, error => {
        console.log('error', error)
        success = false
        message = "审核失败，请联系管理员"
      })
    } else {
      await db.collection('userInfo').add({
        data: {
          _openid: card._openid,
          nickName: card.userInfo.nickName,
          point: addPoint,
          avatarUrl: card.userInfo.avatarUrl,
          distance: distance,
          calorie: calorie,
          time: time
        },
      }).then(res => {
        console.log('res', res)
        success = true
        message = "审核成功"
      }, error => {
        console.log('error', error)
        success = false
        message = "审核失败，请联系管理员"
      })
    }

  }
  return {
    success: success,
    message: message
  }
}

/**
 * 计算单项得分
 * 
 * @param {*} rules 
 * @param {*} card 
 */
function calculatePoint(user, rules, card, totalTypePoint) {
  var addPoint = 0
  if (card.type.index == 5) {
    return addPoint = card.point
  }

  for (var rule of rules.data) {
    if (rule.typeId == card.type.index) {
      switch (rule.typeId) {
        case 0:  // 跑步卡
          console.log(user.team)
          console.log("card.distance：" + card.distance)
          let distance = parseFloat(card.distance)
          if (distance >= 5.0 && distance < 10.0) {
            addPoint = 2
          } else if (distance >= 10.0 && distance < 15.0) {
            addPoint = 4
          } else if (distance >= 15.0 && distance < 20.0) {
            addPoint = 7
          }else if (distance >= 20.0) {
            addPoint = 10
          }else{
            addPoint = 0
          }
          
          if (totalTypePoint + addPoint > rule.weekMaxPoint) {
            addPoint = rule.weekMaxPoint - totalTypePoint
            //有人在第一周已经打了超出的卡了 修正一下
            if (addPoint < 0) {
              addPoint = 0
            }
          }
          break
        case 1: // 力量卡
          let time = parseFloat(card.time);
          if (time >= 30.0 && time < 60.0) {
            addPoint = 2;
          } else if (time >= 60.0 && time < 90.0) {
            addPoint = 4;
          } else if (time >= 90.0) {
            addPoint = 6
          } else addPoint = 0
          // addPoint = Math.floor(card.time / rule.measure * rule.point) + 1
          if (addPoint > rule.maxPoint) {
            addPoint = rule.maxPoint
          }
          if (totalTypePoint + addPoint > rule.weekMaxPoint) {
            addPoint = rule.weekMaxPoint - totalTypePoint
            //有人在第一周已经打了超出的卡了 修正一下
            if (addPoint < 0) {
              addPoint = 0
            }
          }
          break
        case 2: // 越野卡（开启打卡-2024.10.7）
        let dis = parseFloat(card.distance) + parseFloat(card.altitude) / 100
        addPoint = Math.floor(dis / rule.measure * rule.point)
        if (dis >= 10.0 && dis < 20.0) {
          addPoint = 6
        } else if (dis >= 21 && dis < 30.0) {
          addPoint = 9
        } else if (dis >= 30) {
          addPoint = 11
        } else {
          addPoint = 0
        }
          if (totalTypePoint + addPoint > rule.weekMaxPoint) {
            addPoint = rule.weekMaxPoint - totalTypePoint
            //有人在第一周已经打了超出的卡了 修正一下
            if (addPoint < 0) {
              addPoint = 0
            }
          }
          break
        case 3:// 跳绳卡
          console.log('rule.weekMaxPoint', rule.weekMaxPoint)
          addPoint = Math.floor(card.ropeNo / rule.measure * rule.point)
          if (addPoint > rule.maxPoint) {
            addPoint = rule.maxPoint
          }
          if (totalTypePoint + addPoint > rule.weekMaxPoint) {
            addPoint = rule.weekMaxPoint - totalTypePoint
            //有人在第一周已经打了超出的卡了 修正一下
            if (addPoint < 0) {
              addPoint = 0
            }
          }
          break
        case 4:// 爬楼卡
          const level = parseFloat(card.level)
          if (level >= 100 && level < 200) {
            addPoint = 2
          } else if(level >= 200){
            addPoint = 4
          } else{
            addPoint = 0
          }
          // addPoint = Math.floor(card.level / rule.measure * rule.point)
          if (addPoint > rule.maxPoint) {
            addPoint = rule.maxPoint
          }
          if (totalTypePoint + addPoint > rule.weekMaxPoint) {
            addPoint = rule.weekMaxPoint - totalTypePoint
            //有人在第一周已经打了超出的卡了 修正一下
            if (addPoint < 0) {
              addPoint = 0
            }
          }
          break
        case 7:
          const timeY = parseFloat(card.time)
          if (timeY >=30 && timeY < 60) {
            addPoint = 1
          } else if(timeY >= 60) {
            addPoint = 2
          } else {
            addPoint = 0
          }
          if (addPoint > rule.maxPoint) {
            addPoint = rule.maxPoint
          }
          if (totalTypePoint + addPoint > rule.weekMaxPoint) {
            addPoint = rule.weekMaxPoint - totalTypePoint
            //有人在第一周已经打了超出的卡了 修正一下
            if (addPoint < 0) {
              addPoint = 0
            }
          }
          break
      }
      console.log('rule.totalTypePoint', totalTypePoint)
      console.log('rule.addPoint', addPoint)
      console.log('rule.weekMaxPoint', rule.weekMaxPoint)
      break;
    }
  }
  console.log("addPoint", addPoint)
  return addPoint
}